package com.umakr.ax.common.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.umakr.ax.common.mapper.RadioStationShowMapper;
import com.umakr.ax.common.model.*;
import com.umakr.ax.common.vo.RadioStationShowVO;
import com.umakr.ax.common.vo.ShowDiscussVO;
import com.umakr.ax.core.base.BaseService;
import com.umakr.ax.oss.service.StsServiceSample;
import com.umakr.ax.utils.FormatPhotoUrlUtil;
import com.umakr.ax.utils.WebUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * ${table.comment} 服务实现类
 * </p>
 *
 * @author Umakr-Code-Generator
 * @since 2017-12-30
 */
@Service
public class RadioStationShowService extends BaseService<RadioStationShowMapper, RadioStationShow>{

    @Autowired
    ShowFabulousService showFabulousService;
    @Autowired
    FavoriteService favoriteService;
    @Autowired
    ShowDiscussService showDiscussService;
    @Autowired
    LableService lableService;
    @Autowired
    CodeService codeService;
    @Autowired
    ShowLableService showLableService;
    @Autowired
    RadioStationService radioStationService;
    @Autowired
    StsServiceSample stsServiceSample;
    @Autowired
    Environment env;

    private static final String OSS_IMG_PATH = "oss.img.path";
    private static final String USER_ID = "user_id";
    private static final String SHOW_ID = "show_id";
    private static final String UNIVERSAL_ID = "universal_id";
    private static final String FAV_TYPE = "fav_type";
    private static final String DEL_STAUS = "del_staus";

    /**
     * 读取电台发布的信息详情
     * @param userId
     * @param id
     * @author Wmdz
     * @since 2018-01-02
     */
    public Map<String, Object> detail(Long userId, Long id) {
        String aliUrl = env.getProperty(OSS_IMG_PATH);
        int errorCode = 1 ;
		String msg = "查询成功";
        Map<String,Object> result = baseMapper.detail(id);
        result.put("rsLogo",FormatPhotoUrlUtil.formatString(aliUrl,result.get("rsLogo")));
        String showAttachmentType = result.get("showAttachmentType").toString();
        String typeImage = "2";
        String typeVideo = "3";
        if(typeImage.equals(showAttachmentType) || typeVideo.equals(showAttachmentType)){
            result.put("showAttachment",FormatPhotoUrlUtil.formatJson(aliUrl,result.get("showAttachment").toString()));
        }
        // 处理秀点赞
        EntityWrapper<ShowFabulous> showFabulousWrapper = new EntityWrapper<>();
        showFabulousWrapper.eq(USER_ID, userId);
        showFabulousWrapper.eq(SHOW_ID, id);
        Integer showFabulousCount = showFabulousService.selectCount(showFabulousWrapper);
        if (showFabulousCount == 0) {
            result.put("userFabulous",0);
        } else {
            result.put("userFabulous",1);
        }

        //处理秀收藏
        EntityWrapper<Favorite> favoriteWrapper = new EntityWrapper<>();
        favoriteWrapper.eq(USER_ID, userId);
        favoriteWrapper.eq(UNIVERSAL_ID, id);
        favoriteWrapper.eq(FAV_TYPE, 0);
        favoriteWrapper.eq(DEL_STAUS, 0);
        Integer favoriteCount = favoriteService.selectCount(favoriteWrapper);
        if (favoriteCount == 0) {
            result.put("userFavorite",0);
        } else {
            result.put("userFavorite",1);
        }
        return resultMap(result,errorCode,msg);
    }

    public Object load(String cityCode,Integer type, Long userId) {
        String aliUrl = env.getProperty(OSS_IMG_PATH);
        Page<RadioStationShowVO> radioStationShowVOPage = null;
        if (type == 0) {
            radioStationShowVOPage = baseMapper.load(cityCode);
            if(cityCode == null || "".equals(cityCode)){
                return radioStationShowVOPage;
            }
        } else {
            radioStationShowVOPage = baseMapper.loadSelf(userId);
        }
        if(radioStationShowVOPage != null){
            for (RadioStationShowVO rsShowVO : radioStationShowVOPage.getRecords()) {
                //修改链接
                rsShowVO.setRsLogo(aliUrl+rsShowVO.getRsLogo());
                if(rsShowVO.getShowAttachmentType() == 2 || rsShowVO.getShowAttachmentType() == 3) {
                    rsShowVO.setShowAttachment(FormatPhotoUrlUtil.formatJson(aliUrl,rsShowVO.getShowAttachment()));
                }
                Long showId = rsShowVO.getId();
                // 处理秀点赞
                EntityWrapper<ShowFabulous> showFabulousWrapper = new EntityWrapper<>();
                showFabulousWrapper.eq(USER_ID, userId);
                showFabulousWrapper.eq(SHOW_ID, showId);
                Integer showFabulousCount = showFabulousService.selectCount(showFabulousWrapper);
                if (showFabulousCount == 0) {
                    rsShowVO.setUserFabulous(0);
                } else {
                    rsShowVO.setUserFabulous(1);
                }

                //处理秀收藏
                EntityWrapper<Favorite> favoriteWrapper = new EntityWrapper<>();
                favoriteWrapper.eq(USER_ID, userId);
                favoriteWrapper.eq(UNIVERSAL_ID, showId);
                favoriteWrapper.eq(FAV_TYPE, 0);
                favoriteWrapper.eq(DEL_STAUS, 0);
                Integer favoriteCount = favoriteService.selectCount(favoriteWrapper);
                if (favoriteCount == 0) {
                    rsShowVO.setUserFavorite(0);
                } else {
                    rsShowVO.setUserFavorite(1);
                }

                //处理秀评论
                List<ShowDiscussVO> topShowDiscuss = showDiscussService.selectTopShowDiscussByShowId(showId,userId);
                //处理头像链接地址
                for (ShowDiscussVO showDiscussVO : topShowDiscuss){
                    showDiscussVO.setHeadImgUrl(FormatPhotoUrlUtil.formatString(aliUrl,showDiscussVO.getHeadImgUrl()));
                }
                if (topShowDiscuss.isEmpty()) {
                    rsShowVO.setShowDiscuss(topShowDiscuss);
                }
            }
        }
        return radioStationShowVOPage;
    }

    public Object listRecommendRadioStationShow(Long rsId,Long userId) {
        String aliUrl = env.getProperty(OSS_IMG_PATH);

        List<RadioStationShowVO> result = baseMapper.listRecommendRadioStationShow(rsId);
        for(RadioStationShowVO vo : result){
            //修改电台logo
            vo.setRsLogo(FormatPhotoUrlUtil.formatString(aliUrl,vo.getRsLogo()));
            if(vo.getShowAttachmentType() == 2 || vo.getShowAttachmentType() == 3){
                vo.setShowAttachment(FormatPhotoUrlUtil.formatJson(aliUrl,vo.getShowAttachment()));
            }

            //处理秀收藏 点赞
            if(userId == null){
                vo.setUserFavorite(0);
                vo.setUserFabulous(0);
            }else {
                // 处理秀收藏
                EntityWrapper<Favorite> favoriteWrapper = new EntityWrapper<>();
                favoriteWrapper.eq(USER_ID, userId);
                favoriteWrapper.eq(UNIVERSAL_ID, vo.getId());
                favoriteWrapper.eq(FAV_TYPE, 0);
                favoriteWrapper.eq(DEL_STAUS, 0);
                Integer favoriteCount = favoriteService.selectCount(favoriteWrapper);
                if (favoriteCount == 0) {
                   vo.setUserFavorite(0);
                } else {
                    vo.setUserFavorite(1);
                }

                // 处理秀点赞
                EntityWrapper<ShowFabulous> showFabulousWrapper = new EntityWrapper<>();
                showFabulousWrapper.eq(USER_ID, userId);
                showFabulousWrapper.eq(SHOW_ID, vo.getId());
                Integer showFabulousCount = showFabulousService.selectCount(showFabulousWrapper);
                if (showFabulousCount == 0) {
                    vo.setUserFabulous(0);
                } else {
                    vo.setUserFabulous(1);
                }
            }
        }
        return result;
    }

    public void updateRadioStationShow(RadioStationShow radioStationShow) {
        baseMapper.updateRadioStationShow(radioStationShow);
    }

    public Object saveRadioStationShow( RadioStationShow show ) {
        String aliUrl = env.getProperty(OSS_IMG_PATH);
        String videoFirstFrameImg = env.getProperty("file.videoFirstFrame.img");
        String lableName = show.getShowLables();
        Long rsId = show.getRsId();
        Long lbId = null;
        //处理标签
        if(lableName != null){
            //判断是不是系统标签
            EntityWrapper<Lable> lableWrapper = new EntityWrapper<>();
            lableWrapper.eq("lb_name", lableName);
            lableWrapper.eq("lb_type", 1);
            Lable lable = lableService.selectOne(lableWrapper);
            if(lable == null){
                EntityWrapper<Code> codeWrapper = new EntityWrapper<>();
                codeWrapper.eq("code_type_name", "custom_lable_color");
                Code code = codeService.selectOne(codeWrapper);
                show.setShowLables(lableName+","+code.getCodeValue());
                //如果是自定义标签需要在标签表中插入一条数据
                Lable lableNew = new Lable();
                lableNew.setLbType(2);
                lableNew.setLbName(lableName);
                lableNew.setLbColor(code.getCodeValue());
                lableService.insert(lableNew);
                lbId = lableNew.getId();
            }else {
                lbId = lable.getId();
                show.setShowLables(show.getShowLables()+","+lable.getLbColor());
            }
        }
        if(rsId != null){
            RadioStation radioStation = radioStationService.queryById(rsId);
            if(radioStation != null){
                show.setRsLogo(radioStation.getRsLogo());
                show.setRsName(radioStation.getRsName());
            }
        }
        //处理时间
        show.setShowPbTime(new Date());

        int typeVideo = 3;
        //截取视频第一帧图片,通过FFMPEG程序
        if(show.getShowAttachmentType() == typeVideo) {
            //FFMPEG程序路径
            Environment environment =  WebUtil.getBean(Environment.class);
            String ffmpegPath = environment.getProperty("ffmpeg.path.video");
            String mediaPicPath = "";
            JSONArray writeOffArray = JSONObject.parseArray(show.getShowAttachment());
            for(Object writeOffObj : writeOffArray){
                JSONObject writeOff = (JSONObject)writeOffObj;
                mediaPicPath = videoFirstFrameImg+File.separator+String.valueOf(System.currentTimeMillis())+".jpg";
                FormatPhotoUrlUtil.transfer(ffmpegPath,aliUrl+writeOff.get("src"),mediaPicPath,
                        "0");
            }

            //通过线程检测当截图完成后上传截图至阿里云并删除本地图片
            FilesMonitor t = new FilesMonitor();
            t.show(mediaPicPath,show.getRsId());

            //拼接第一帧图片路径并set
            File file = new File(mediaPicPath);
            String newShowAttachment = show.getShowAttachment().substring(0,show.getShowAttachment().length()-1);
            String newJsonString = newShowAttachment+",{\"videoFirstImgSrc\":\""+"test/videoFirstFrameImg/"+file.getName()+"\"}]";
            show.setShowAttachment(newJsonString);
        }

        baseMapper.insertRadioStationShow(show);
        //处理电台秀和标签对应关系
        Long showId = show.getId();
        if(lbId != null){
            ShowLable showLable = new ShowLable();
            showLable.setLbId(lbId);
            showLable.setShowId(showId);
            showLableService.insert(showLable);
        }
        //设置好头像路径 和 附件路径
        show.setRsLogo(FormatPhotoUrlUtil.formatString(aliUrl,show.getRsLogo()));
        show.setShowAttachment(FormatPhotoUrlUtil.formatJson(aliUrl,show.getShowAttachment()));
        return resultMap(show,1,"发布成功");
    }


    public class FilesMonitor implements Runnable {
        String mediaPicPath;
        Long rsId;
        @Override
        public void run() {
            while (true) {
                try {
                    // 设置每隔1毫秒检测一次
                    Thread.sleep(1);
                    File file = new File(mediaPicPath);
                    if (file.exists() && file.isFile()) {
                        stsServiceSample.fileUploads(rsId,file,"test/videoFirstFrameImg/");
                        Boolean delect = file.delete();
                        if(delect) {
                            break;
                        }
                    }

                } catch (InterruptedException e) {
                    logger.debug(e);
                    Thread.currentThread().interrupt();
                }
            }
        }


        public void setTar(String mediaPicPath, Long rsId) {
            this.mediaPicPath = mediaPicPath;
            this.rsId = rsId;
        }

        /**启动线程*/
        public void show(String mediaPicPath, Long rsId) {
            FilesMonitor t = new FilesMonitor();
            t.setTar(mediaPicPath,rsId);
            Thread tread = new Thread(t);
            tread.start();
        }
    }

    public Object delRadioStationShow( Long showId ){
        int code = 0;
        String msg = "";

        if(showId != null){
            RadioStationShow sd = queryById(showId);
            if(sd != null){
                sd.setDelStatus(1);
                updateRadioStationShow(sd);
                code = 1;
                msg = "电台秀删除成功";
            }else{
                msg = "未找到相关电台秀";
            }
        }else{
            msg = "电台秀已被删除";
        }

        return resultMap(code,msg);
    }


}
